import { useRouter } from "next/router";
import SessionsTable from "@/src/components/table/use-cases/sessions";
import Page from "@/src/components/layouts/page";
import { SessionsOnboarding } from "@/src/components/onboarding/SessionsOnboarding";
import { api } from "@/src/utils/api";
import { useTranslation } from "@/src/utils/i18n";
import { useEffect } from "react";

export default function Sessions() {
  const router = useRouter();
  const projectId = router.query.projectId as string;
  const { t } = useTranslation();

  useEffect(() => {
    const handler = (e: MessageEvent) => {
      if (e.data && e.data.type === "requestHeight") {
        const height =
          document.documentElement.scrollHeight ||
          document.body.scrollHeight;
        (e.source as Window | null)?.postMessage(
          { type: "contentHeight", height },
          e.origin || "*",
        );
      }
    };
    window.addEventListener("message", handler);
    return () => window.removeEventListener("message", handler);
  }, []);

  const { data: hasAnySession, isLoading } = api.sessions.hasAny.useQuery(
    { projectId },
    {
      enabled: !!projectId,
      trpc: {
        context: {
          skipBatch: true,
        },
      },
      refetchInterval: 10_000,
    },
  );

  const showOnboarding = !isLoading && !hasAnySession;

  return (
    <Page
      headerProps={{
        title: t("pages.sessions.title"),
        help: {
          description: t("pages.sessions.description"),
          href: t("pages.sessions.helpUrl"),
        },
      }}
      scrollable={showOnboarding}
    >
      {/* Show onboarding screen if user has no sessions */}
      {showOnboarding ? (
        <SessionsOnboarding />
      ) : (
        <SessionsTable projectId={projectId} />
      )}
    </Page>
  );
}
